var express = require('express')
var router = express.Router()
const models = require('../../models')
const Op = models.Sequelize.Op
const {success, error} = require('../../utils/message')
const toBoolean = require('../../utils/to-boolean')
const checkPermission = require('../../middlewares/check-permission');

// 商品列表
router.get('/', checkPermission(), async function (req, res, next) {
    const name = req.query.name
    const categoryId = req.query.categoryId
    const brandId = req.query.brandId
    const discount = req.query.discount
    const emergency = req.query.emergency
    const nourishing = req.query.nourishing
    const prevention = req.query.prevention
    const commonUse = req.query.commonUse
    const cardiovascular = req.query.cardiovascular
    const createdAt = req.query.createdAt
    const currentPage = parseInt(req.query.currentPage) || 1
    const pageSize = parseInt(req.query.pageSize) || 12
    const where = {}
    // 模糊查询名称
    if (name) {
        where.name = {
            [Op.like]: '%' + name + '%'
        }
    }
    if (categoryId) {
        where.categoryId = {
            [Op.eq]: categoryId
        }
    }
    if (brandId) {
        where.brandId = {
            [Op.eq]: brandId
        }
    }
    // 特惠
    if (discount) {
        where.discount = {
            [Op.eq]: toBoolean(discount)
        }
    }
    // 应急
    if (emergency) {
        where.emergency = {
            [Op.eq]: toBoolean(emergency)
        }
    }
    // 滋补
    if (nourishing) {
        where.nourishing = {
            [Op.eq]: toBoolean(nourishing)
        }
    }
    // 防疫
    if (prevention) {
        where.prevention = {
            [Op.eq]: toBoolean(prevention)
        }
    }
    // 常用
    if (commonUse) {
        where.commonUse = {
            [Op.eq]: toBoolean(commonUse)
        }
    }
    // 心脑血管
    if (cardiovascular) {
        where.cardiovascular = {
            [Op.eq]: toBoolean(cardiovascular)
        }
    }
    // 日期范围
    if (createdAt) {
        // const dateTimes = createdAt.split(',') // 如果提交过来的是字符串需把字符串转换成数组
        const start = createdAt[0] + ' 00:00:00'
        const end = createdAt[1] + ' 23:59:59'
        where.createdAt = {
            [Op.between]: [start, end]
        }
    }

    const result = await models.Product.findAndCountAll({
        include: [
            {
                model: models.Category,
                as: 'category'
            },
            {
                model: models.Brand,
                as: 'brand'
            },
            {
                model: models.Tag,
                as: 'tags'
            },
            {
                model: models.ProductGallery,
                as: 'galleries'
            }
        ],
        distinct: true, // 由于每个商品有很多标签、也有很多相册，模型中定义了一对多或多对多关系，使用 distinct: true 可排除关联表中的统计数据
        order: [
            ['id', 'DESC']
        ],
        where: where,
        offset: (currentPage - 1) * pageSize,
        limit: parseInt(pageSize)
    }).catch(err => {
        console.log(err);
    })

    const data = {
        products: result.rows,
        pagination: {
            currentPage: parseInt(currentPage),
            pageSize: parseInt(pageSize),
            total: result.count
        }
    }
    success(res, '查询成功', data)
})

// 查询单条
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const product = await models.Product.findOne({
        where: {id: id},
        include: [
            {
                model: models.Brand,
                as: 'brand'
            },
            {
                model: models.Tag,
                as: 'tags'
            },
            {
                model: models.ProductGallery,
                as: 'galleries'
            }
        ],
    })
    success(res, '查询成功', {product})
})

// 新增
router.post('/', checkPermission(), async function (req, res, next) {
    // console.log(req.body)
    const name = req.body.name
    const categoryId = req.body.categoryId
    const price = req.body.price
    const onsale = toBoolean(req.body.onsale)
    const recommend = toBoolean(req.body.recommend)
    const discount = toBoolean(req.body.discount)
    const emergency = toBoolean(req.body.emergency)
    const nourishing = toBoolean(req.body.nourishing)
    const prevention = toBoolean(req.body.prevention)
    const commonUse = toBoolean(req.body.commonUse)
    const cardiovascular = toBoolean(req.body.cardiovascular)
    const tags = req.body.tags
    const imgs = req.body.imgs

    if (!name) {
        return error(res, '请填写商品名称')
    }

    if (!categoryId) {
        return error(res, '请选择商品所属分类')
    }

    if (!price) {
        return error(res, '请填写商品价格')
    }

    const body = {
        ...req.body,
        onsale: onsale,
        recommend: recommend,
        discount: discount,
        emergency: emergency,
        nourishing: nourishing,
        prevention: prevention,
        commonUse: commonUse,
        cardiovascular: cardiovascular,
    }
    const product = await models.Product.create(body).catch(err => {
        console.log(err); // 方便打印错误
    })

    // 往中间表同步标签数据
    const result = await models.Tag.findAll({where: {id: tags}})
    product.setTags(result)

    // 往商品相册表循环插值
    let Product_galleries = imgs.map(item => {
        return {
            productId: product.id,
            imgs: item,
        }
    })
    await models.ProductGallery.bulkCreate(Product_galleries)

    success(res, '新增成功', {product})
})

// 修改
router.put('/:id', checkPermission(), async function (req, res, next) {
    // res.json(req.body.tags);return
    const id = req.params.id
    const name = req.body.name
    const categoryId = req.body.categoryId
    const price = req.body.price
    const onsale = toBoolean(req.body.onsale)
    const recommend = toBoolean(req.body.recommend)
    const discount = toBoolean(req.body.discount)
    const emergency = toBoolean(req.body.emergency)
    const nourishing = toBoolean(req.body.nourishing)
    const prevention = toBoolean(req.body.prevention)
    const commonUse = toBoolean(req.body.commonUse)
    const cardiovascular = toBoolean(req.body.cardiovascular)
    const tags = req.body.tags
    const imgs = req.body.imgs

    if (!name) {
        return error(res, '请填写商品名称')
    }

    if (!categoryId) {
        return error(res, '请选择商品所属分类')
    }

    if (!price) {
        return error(res, '请填写商品价格')
    }

    const product = await models.Product.findByPk(id)
    if (!product) {
        return error(res, '当前商品不存在，无法修改')
    }

    const body = {
        ...req.body,
        onsale: onsale,
        recommend: recommend,
        discount: discount,
        emergency: emergency,
        nourishing: nourishing,
        prevention: prevention,
        commonUse: commonUse,
        cardiovascular: cardiovascular,
    }

    product.update(body)

    // 往中间表同步标签数据
    if (tags) {
        await models.Tag.findAll({where: {id: tags}})
        product.setTags(tags)
    }
    // 往商品相册表循环插值
    if (imgs) {
        let Product_galleries = imgs.map(item => {
            return {
                productId: product.id,
                imgs: item,
            }
        })
        await models.ProductGallery.bulkCreate(Product_galleries)
    }

    success(res, '修改成功', {product})
})

// 删除相册
router.delete('/delGallery/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const gallery = await models.ProductGallery.findOne({where: {id: id}})
    gallery.destroy()
    success(res, '删除成功')
})

// 删除商品
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id

    // 删除商品
    const product = await models.Product.findByPk(id)
    product.destroy()

    // 删除对应的标签
    const tags = await models.ProductTag.findAll({where: {productId: id}})
    const tagIds = []
    tags.map(item => {
        tagIds.push(item.tagId)
    });

    await models.ProductTag.destroy({
        where: {
            tagId: {
                [Op.in]: tagIds
            },
            productId: id
        }
    })

    // 删除对应的相册
    const galleries = await models.ProductGallery.findAll({where: {productId: id}})
    const galleryIds = []
    galleries.map(item => {
        galleryIds.push(item.id)
    });

    await models.ProductGallery.destroy({
        where: {
            id: {
                [Op.in]: galleryIds
            }
        }
    })

    success(res, '删除成功')
})

// 批量删除商品
router.post('/delete_checked', checkPermission(), async function (req, res, next) {
    await models.Product.destroy({
        where: {
            id: {
                [Op.in]: req.body.checked_id
            }
        }
    })
    success(res, '批量删除成功')
});

// 修改商品属性
router.patch('/:id/change_attr', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const type = req.body.type

    if (!type) {
        return error(res, 'type类型不能为空')
    }

    const types = ['recommend', 'discount', 'emergency', 'nourishing', 'prevention', 'commonUse', 'cardiovascular', 'onsale']
    if (types.indexOf(type) === '-1') {
        return error(res, 'type类型错误，只能是recommend、discount、emergency、nourishing、prevention、commonUse、cardiovascular、onsale中的一种')
    }

    const product = await models.Product.findByPk(id)
    if (!product) {
        return error(res, '当前商品不存在，无法修改')
    }

    const body = {}
    body[type] = !product[type]
    product.update(body)
    success(res, '修改成功', {product})
})


module.exports = router
